class happyLocalStorage {
  constructor() {

  }

  judgeDataType(val) {
    return Object.prototype.toString.call(val).slice(8, -1);
  }

  _delLocalStorage(getName) {//删除已经过期的LocalStorage
    let getLocalStorageValue = localStorage.getItem(getName);

    try {
      getLocalStorageValue = JSON.parse(getLocalStorageValue);
    } catch (error) {
      getLocalStorageValue = getLocalStorageValue;
    };

    if (this.judgeDataType(getLocalStorageValue) == "Object" && !!getLocalStorageValue._effectiveTime) {
      let res = JSON.parse(localStorage.getItem(getName));
      let effectiveTime = new Date(res._effectiveTime).getTime();
      if (new Date().getTime() - effectiveTime > 0) {//过期
        localStorage.removeItem(getName);//删除对应的key
      }
    }
  }

  _initLocalStorage() {//初始化
    let len = localStorage.length;  // 获取长度
    let arr = [];
    if (len > 0) {
      for (let i = 0; i < len; i++) {
        let getKey = localStorage.key(i);
        arr.push(getKey);
      };
      arr.forEach(item => {//这里面存储的一定是有值的LocalStorage
        this._delLocalStorage(item)
      })
    };
  }

  /**
   * 功能:设置LocalStorage的值和过期时间
   * @param {*} setName:设置的名称 string
   * @param {*} setValue:设置的值 any
   * @param {*} expiresObj:过期时间 {}/{timeScale:'秒/分/时 日/月/年',timeSize:number} 
   */
  setLocalStorage(setName, setValue, expiresObj = null) {
    if (expiresObj == null) {//如果用户不输入第三个参数
      let JSONStringify = JSON.stringify(setValue);
      localStorage.setItem(setName, JSONStringify);
    } else {//这里面输出的一定是一个已经JSON.stringify好的对象
      if (Object.keys(expiresObj).length == 0) {//输入的是一个空对象 设置默认过期时间:15分钟
        let newDate = new Date();//获取当前的时间对象
        let nowTimeStamp = newDate.getTime();//获取当前时间对象的时间戳
        nowTimeStamp += (1000 * 60 * 15);//将现在的时间戳和设置过期时间期间产生的时间戳 累加
        newDate.setTime(nowTimeStamp);//将累加的时间戳设置到过期时间上
        expiresObj[setName] = setValue;//将传入的名称和值以key/value的形式挂载到expiresObj上
        expiresObj._effectiveTime = newDate;//将累加好的时间挂载到expiresObj
        let stringifyExpiresObj = JSON.stringify(expiresObj);//将expiresObj转成字符串
        localStorage.setItem(setName, stringifyExpiresObj);//设置localStorage

        setTimeout(() => {//页面一直开着，到了过期时间就删掉
          this.delLocalStorage(setName);
        }, 1000 * 60 * 15);
      } else {//输入的不是空对象
        let newDate = new Date();
        let nowTimeStamp = newDate.getTime();
        let timeout = null;
        switch (expiresObj.timeScale) {//判断时间规格
          case '秒':
            nowTimeStamp += (1000 * expiresObj.timeSize);
            timeout = (1000 * expiresObj.timeSize);
            break;
          case '分':
            nowTimeStamp += (1000 * 60 * expiresObj.timeSize);
            timeout = (1000 * 60 * expiresObj.timeSize);
            break;
          case '时':
            nowTimeStamp += (1000 * 60 * 60 * expiresObj.timeSize);
            timeout = (1000 * 60 * 60 * expiresObj.timeSize);
            break;
          case '日':
            nowTimeStamp += (1000 * 60 * 60 * 24 * expiresObj.timeSize);
            timeout = (1000 * 60 * 60 * 24 * expiresObj.timeSize);
            break;
          case '月':
            nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * expiresObj.timeSize);
            timeout = (1000 * 60 * 60 * 24 * 30 * expiresObj.timeSize);
            break;
          case '年':
            nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * 12 * expiresObj.timeSize);
            timeout = (1000 * 60 * 60 * 24 * 30 * 12 * expiresObj.timeSize);
            break;

          default:
            break;
        }
        newDate.setTime(nowTimeStamp);//将累加的时间戳设置到过期时间上
        expiresObj[setName] = setValue;
        expiresObj._effectiveTime = newDate;
        let stringifyExpiresObj = JSON.stringify(expiresObj);
        localStorage.setItem(setName, stringifyExpiresObj);

        setTimeout(() => {
          this.delLocalStorage(setName);
        }, timeout);
      }
    }
  }

  /**
   * 功能:获取LocalStorage的值
   * @param {*} getName:获取的名称
   */
  getLocalStorage(getName) {
    let getLocalStorageValue = localStorage.getItem(getName);

    try {
      getLocalStorageValue = JSON.parse(getLocalStorageValue);
    } catch (error) {
      getLocalStorageValue = getLocalStorageValue;
    };

    if (this.judgeDataType(getLocalStorageValue) == "Object" && !!getLocalStorageValue._effectiveTime) {
      let res = JSON.parse(localStorage.getItem(getName));//根据getName获取localStorage中对应的存储对象
      let effectiveTime = new Date(res._effectiveTime).getTime();//获取当初设置的时候的过期时间时间戳
      if (new Date().getTime() - effectiveTime < 0) {//如果当前的时间戳<当初设置的时候的过期时间时间戳 证明：没过期
        return JSON.parse(localStorage.getItem(getName))[getName];
      } else {//过期
        localStorage.removeItem(getName);
        return null;
      }
    } else {
      return getLocalStorageValue;
    }
  }

  delLocalStorage(name) {//删除指定的LocalStorage
    localStorage.removeItem(name);
  }

  delAllLocalStorage() {//删除全部的LocalStorage
    localStorage.clear();
  }
}

let hl = new happyLocalStorage();
hl._initLocalStorage();
setInterval(() => {
  console.log('只要引入了我这个方法，并且浏览器一直打开，每隔15分钟会自动验证有没有过期的localStorage');
  hl._initLocalStorage();
}, 1000 * 60 * 15);

export {
  hl
}